package controllers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import controllers.CRUD.ObjectType;
import dtos.OrganizacionDto;
import jxl.write.WriteException;
import models.Auditoria;
import models.Organizacion;
import models.SubBase;
import play.db.Model;
import play.db.jpa.JPA;
import play.exceptions.TemplateNotFoundException;
import play.mvc.With;
import utils.ColumnFilters;

@With(Secure.class)
public class Auditorias extends ArcadiaCRUD {
	
	public static void list(int page, String search, String searchFields, String orderBy, String order) {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        if (page < 1) {
            page = 1;
        }
        String where = null;
	    if (search!=null && !"".equals(search.trim())){	    	
	    	where = " (upper(user.username) like '%";
	    	where = where.concat(search.toUpperCase());
	    	where = where.concat("%')");
	    	search = null;
	    }
	    orderBy = null;
	    searchFields=null;
	    
        List<Model> objects = type.findPage(page, search, searchFields, orderBy, order, where);
        Long count = type.count(search, searchFields, where);
        Long totalCount = type.count(null, null, where);
        try {
            render(type, objects, count, totalCount, page, orderBy, order);
        } catch (TemplateNotFoundException e) {
            render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order);
        }
    }
	
	 public static void show(String id) throws Exception {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Model object = type.findById(id);
        Auditoria auditoria = (Auditoria)object;
        List<OrganizacionDto> results = SubBases.getExportResult(auditoria.subbase.organizaciones);
	    
		String temporalName = String.valueOf(System.currentTimeMillis());
		File file;
		try {
			ColumnFilters filters = new ColumnFilters();
			filters.EMPRESA_REPARTICION_TITLE = true;
			file = XLSExportHelper.write(temporalName, results, filters);
			String name = "subbase_".concat(auditoria.subbase.nombre).concat(".xls");
			renderBinary(file, name);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		list(1, null, null, null, null);   
    }
	 
}
